import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { getHash } from '@/utils/hash';
import { UserService } from '../user/user.service';

@Injectable()
export class AuthService {
    constructor(
        private userService: UserService,
        private jwtService: JwtService
    ) {}

    async signIn(username: string, password: string) {
        const user = await this.userService.findOne({ username, password: getHash(password) });
        if (!user) {
            throw new BadRequestException('the user does not exist');
        }

        const payload = { username: user.username };
        return {
            userId: user._id,
            username: user.username,
            accessToken: await this.jwtService.signAsync(payload),
        };
    }
}
